# encoding:utf-8
import os
from utils.file_handling.txt_handling import write_txt
from config.all_paths import result_txt_path
from utils.file_handling.log_handling import logger
from utils.variables_tool.handling_global_variables import get_value_from_json
from utils.mysql_tool.mysql_control import Mysql
from config.global_variable import CMDINPUT

class ResponseAsserter:
    def __init__(self, data, res, excelName):
        self.data = data
        self.res = res
        self.excelName = excelName
        self.result_txt_path_new = os.path.join(result_txt_path, f'{excelName}.txt')

    def write_assertion_result(self, status):
        """
        Write the assertion result to a text file.
        """
        write_txt(text_file=self.result_txt_path_new, data=self.data["id"] + f"|{status}" + "|" + self.res.text )

    def assert_status_code(self):
        """
        Assert the status code.
        """
        status_code = int(self.data.get('status_code'))
        if status_code not in ['', None]:
            assert self.res.status_code == status_code, f"""
            status_code assertion failed: Expected {status_code}, got {self.res.status_code},
            输出日志：{logger.error('status_code 断言失败')},
            将结果写入txt文件：{self.write_assertion_result('fail')}
            """

    def assert_msg(self):
        """
        Assert the message.
        """
        msg = self.data.get('msg')
        if msg not in ['', None]:
            assert self.res.json()['msg'] == msg, f"""
            msg assertion failed: Expected {msg}, got {self.res.json()['msg']},
            输出日志：{logger.error('msg 字段断言失败')},
            将结果写入txt文件：{self.write_assertion_result("fail")}"""

    def assert_check_data(self):
        """
        Assert the check data.{}
        """
        check_data = self.data.get('check_data')
        if check_data not in ['', None]:
            check_data = eval(check_data)
            for key in check_data.keys():
                assert_value = check_data[key]
                return_value = get_value_from_json(key, self.res.json(), [])
                if len(return_value) == 0:
                    assert False, f"""
                    check data assertion failed: Expected {assert_value}, got None,
                    输出日志：{logger.error(f"{key} 字段 断言失败")},
                    将结果写入txt文件：{self.write_assertion_result("fail")}"""
                if assert_value not in return_value:
                    assert False, f"""
                    check data assertion failed: Expected {assert_value}, got {return_value},
                    输出日志：{logger.error(f"{key} 字段 断言失败")},
                    将结果写入txt文件：{self.write_assertion_result("fail")}"""

    def assert_check_sql(self):
        """
        Assert the check SQL.{}
        """
        check_sql = self.data['check_sql']
        if check_sql not in ['', None]:
            check_sql = eval(check_sql)
            for key in check_sql.keys():
                sql = check_sql[key]
                mysql_data = Mysql(CMDINPUT['host'], CMDINPUT['username1'], CMDINPUT['password1'], CMDINPUT['db']).get(sql)[key]
                res_data = get_value_from_json(key, self.res.json(), [])[0]
                assert mysql_data == res_data, f"""
                check SQL assertion failed: Expected {mysql_data}, got {res_data},
                输出日志：{logger.error(f"{key} 字段 断言失败")},
                将结果写入txt文件：{self.write_assertion_result("fail")}"""

    def assert_response(self):
        """
        Assert the response.
        """
        logger.info(f"接口请求状态码: {self.res.status_code}")
        logger.info(f"接口响应体: {self.res.json()}")

        self.assert_status_code()
        self.assert_msg()
        self.assert_check_data()
        self.assert_check_sql()

        logger.info('断言通过')
        self.write_assertion_result("pass")
